{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "Case Study: Debugging in Classification.ipynb",
      "version": "0.3.2",
      "provenance": [
        {
          "file_id": "1K6dyxkBfrXVxppRzGHUnMFnK2Otnlp5i",
          "timestamp": 1541016529771
        }
      ],
      "collapsed_sections": [
        "vrr7QBAu_oeC",
        "nKdUi_QENxXp",
        "dqnRGq2UCEYP"
      ],
      "last_runtime": {
        "build_target": "//learning/brain/python/client:colab_notebook",
        "kind": "private"
      }
    },
    "kernelspec": {
      "display_name": "Python 2",
      "name": "python2"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "vrr7QBAu_oeC"
      },
      "source": [
        "#### Copyright 2018 Google LLC."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "cellView": "both",
        "colab_type": "code",
        "id": "36xim66b_oeE",
        "colab": {}
      },
      "source": [
        "# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "MvIx0zxzE93Y"
      },
      "source": [
        "# Case Study: Debugging in Classification"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "9tNgLQzd1QHX"
      },
      "source": [
        "This Colab quickly demonstrates a few concepts related to debugging classification models. You will explore potential problems in implementing these tasks:\n",
        "\n",
        "* Calculating loss for classification problems.\n",
        "* Optimizing your model\n",
        "* Applying regularization.\n",
        "* Following best practices in development and debugging.\n",
        "\n",
        "Please **make a copy** of this Colab before running it. Click on *File*, and then click on *Save a copy in Drive*."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "0X7dDkLFFCYT"
      },
      "source": [
        "## Load MNIST Data"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "vmtkGlmC0a0O"
      },
      "source": [
        "MNIST is a dataset of images of the numbers 0 to 9. The problem is to classify the images as numbers. Setup libraries and load the MNIST dataset. Display the first few rows to verify that the data loaded. You'll explore the data format after the data loads."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "RNYSqbAcFOIs",
        "colab": {}
      },
      "source": [
        "# Reset environment for a new run\n",
        "% reset -f\n",
        "\n",
        "# Load Libraries\n",
        "from os.path import join # for joining file pathnames\n",
        "import pandas as pd\n",
        "import tensorflow as tf\n",
        "from tensorflow import keras\n",
        "import numpy as np\n",
        "import matplotlib.pyplot as plt\n",
        "import unittest\n",
        "import sys\n",
        "\n",
        "# Set Pandas display options\n",
        "pd.options.display.max_rows = 10\n",
        "pd.options.display.float_format = '{:.1f}'.format\n",
        "\n",
        "# Load data\n",
        "mnistDf_backup = pd.read_csv(\n",
        "  \"https://download.mlcc.google.com/mledu-datasets/mnist_train_small.csv\",\n",
        "  sep=\",\",\n",
        "  header=None)\n",
        "# Shuffle data\n",
        "mnistDf_backup.sample(frac=1).reset_index(drop=True)\n",
        "# Use the first 5000 examples for faster prototyping\n",
        "mnistDf = mnistDf_backup[0:5000]\n",
        "\n",
        "mnistDf.head()"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "Z70hEJlEGyMJ"
      },
      "source": [
        "## Understanding the Data Format"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "kg0-25p2mOi0"
      },
      "source": [
        "Each row represents one labeled example. Column 0 represents the label that a human rater has assigned for one handwritten digit. For example, if Column 0 contains '6', then a human rater interpreted the handwritten character as the digit '6'.  The ten digits 0-9 are each represented, with a unique class label for each possible digit. Thus, this is a multi-class classification problem with 10 classes."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "PQ7vuOwRCsZ1"
      },
      "source": [
        "![img](https://www.tensorflow.org/versions/r0.11/images/MNIST-Matrix.png)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "dghlqJPIu8UM"
      },
      "source": [
        "Columns 1 through 784 contain the feature values, one per pixel for the 28×28=784 pixel values. The pixel values are on a gray scale in which 0 represents white, 255 represents black, and values between 0 and 255 represent shades of gray. Most of the pixel values are 0; you may want to take a minute to confirm that they aren't all 0.  Modify the form below and run the code to view data for a given example."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "cellView": "form",
        "colab_type": "code",
        "id": "2ZkrL5MCqiJI",
        "colab": {}
      },
      "source": [
        "showExample = 1000 # @param\n",
        "digitData = np.reshape(mnistDf.iloc[showExample,0:-1],[28,28])\n",
        "print digitData"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "NdGR7XJFG3SC"
      },
      "source": [
        "## Do you have Imbalanced Classes?"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "iaCeo87dGq6F"
      },
      "source": [
        "As we read in the course, imbalanced classes make classification harder. Let's look at the distribution of classes. Do you have imbalanced classes?"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "ovuBykz5GCHl",
        "colab": {}
      },
      "source": [
        "%hide_result # hides result of cell computation\n",
        "# Calculate the number of classes\n",
        "numClasses = mnistDf.iloc[:,0].unique().shape[0]\n",
        "# Plot histogram of class distribution\n",
        "plt.hist(mnistDf.iloc[:,0], bins=range(numClasses+1))\n",
        "plt.xticks(range(numClasses+1))"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "a7b5jJzMFd9f"
      },
      "source": [
        "The preceding graph shows that the 10 classes are roughly equally represented."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "Z9gUThwlOjRu"
      },
      "source": [
        "## Shuffle and Split Dataset"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "yPd1qfBGOmot"
      },
      "source": [
        "As part of [Data Debugging](https://developers.google.com/machine-learning/testing-debugging/common/data-errors) best practices, ensure your splits are statistically equivalent by shuffling your data to remove any pre-existing order."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "9dKZM0l8Om_Q",
        "colab": {}
      },
      "source": [
        "# Shuffle data\n",
        "mnistDf = mnistDf.sample(frac=1).reset_index(drop=True)\n",
        "\n",
        "# Split dataset into data and labels\n",
        "mnistData = mnistDf.iloc[:,1:-1].copy(deep=True)\n",
        "mnistLabels = mnistDf.iloc[:,0].copy(deep=True)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "i7cOxjDqJW1r"
      },
      "source": [
        "## Process Data"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "T8Hsfx4OJh4J"
      },
      "source": [
        "Scale the data values to `[0,1]` since the values are bounded to `[0,255]` and do not contain outliers. Then check that the scaled data values are as expected by generating summary statistics using the `DataFrame.describe()` function.\n",
        "\n",
        "Run the following cell to scale data and generate statistics. This cell takes a few minutes to run."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "xz6glQVeJhGa",
        "colab": {}
      },
      "source": [
        "def minMaxScaler(arr):\n",
        "  min = np.min(arr)\n",
        "  max = np.max(arr)\n",
        "  arr = (arr-min)/max\n",
        "  return arr\n",
        "\n",
        "for featureIdx in range(mnistData.shape[1]):\n",
        "  mnistData.iloc[:,featureIdx] = minMaxScaler(mnistData.iloc[:,featureIdx])\n",
        "\n",
        "mnistData.describe()"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "ja7-yiPaNSqQ"
      },
      "source": [
        "Oh no! Some of your features are all `NaN`. What do you think the cause is? Hint: While NaNs have many causes, in this case, the NaN values are caused by the properties of your data. Use the next code cell to explore your data. Then check the next cell for the solution. Try to find the solution yourself. Debugging `NaN`s and exploring your data are important skills."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "MDcTFax_FaAh",
        "colab": {}
      },
      "source": [
        "# First reload your data\n",
        "mnistData = mnistDf.iloc[:,1:-1].copy(deep=True)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "lPRf41XwNlSJ",
        "colab": {}
      },
      "source": [
        "# Explore your data"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "nKdUi_QENxXp"
      },
      "source": [
        "### Solution"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "OCYR63qR249Y"
      },
      "source": [
        "Start exploring your data by generating a high-level summary using `Dataframe.describe()`."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "KrZUagAw24oS",
        "colab": {}
      },
      "source": [
        "mnistData.describe()"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "cp3rP2saNyup"
      },
      "source": [
        "Because some of the feature columns are all zeros, the scaling function divided by 0 (because `np.max` returns 0). The division by 0 resulted in NaN values. This result shows you how easily NaNs can arise in engineered data. The `describe` function will not detect every occurrence of NaN (or None). Instead,  use the command `DataFrame.isnull().any()`.\n",
        "\n",
        "*Note*: Given the maximum value of the feature data is 255, you could simply divide the input by 255 instead of using min-max scaling, and avoid introducing NaNs. However, this example purposely uses min-max scaling to show how NaNs can appear in engineered data.\n",
        "\n",
        "Now let's try scaling the data again."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "YSV3SNG2LNp2",
        "colab": {}
      },
      "source": [
        "# Redefine the scaling function to check for zeros\n",
        "def minMaxScaler(arr):\n",
        "  max = np.max(arr)\n",
        "  if(max!=0):  # avoid /0\n",
        "    min = np.min(arr)\n",
        "    arr = (arr-min)/max\n",
        "  return arr\n",
        "\n",
        "# Reload data\n",
        "mnistData = mnistDf.iloc[:,1:-1].copy(deep=True)\n",
        "\n",
        "# Scale data\n",
        "for featureIdx in range(mnistData.shape[1]):\n",
        "  mnistData.iloc[:,featureIdx] = minMaxScaler(mnistData.iloc[:,featureIdx])"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "_xXmVNVJXrG1"
      },
      "source": [
        "You should follow best practice and prevent this bug from recurring by writing a unit test to check for not having `NaN` values in your engineered data."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "9IBsKY3i6itJ"
      },
      "source": [
        "## Remove All-Zero Features?"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "o7BIOScX6kp5"
      },
      "source": [
        "You might think that getting NaNs and discovering that some features were all-zero is good luck because those features can be discarded. However, your training data and validation data might have different all-zero features. Since you should not use validation data to make modeling decisions, you cannot remove only those features that are all-zero in both. Furthermore, data in the future might have different characteristics. There are pros and cons in either case. This Colab keeps the features since reducing the feature set is not a concern."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "HE0WOm7O3TGl"
      },
      "source": [
        "## Establish Baseline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "PAWzL8sW3U9V"
      },
      "source": [
        "Following development best practices, you should establish a baseline. The simplest baseline is predicting the most common class. You saw that the most common class is 1. Let's check the accuracy when always predicting 1."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "PhT7hh6j5HmA",
        "colab": {}
      },
      "source": [
        "np.sum(mnistLabels==1)*1.0/mnistLabels.shape[0]*100"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "VOE2yBOK5fQw"
      },
      "source": [
        "Your baseline accuracy is about 11%. Should be easy to beat, right?"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "B6AOgLcC5nwp"
      },
      "source": [
        "## Train a Linear Model"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "2hH-T1mn5pao"
      },
      "source": [
        "Let's start nice and easy with a linear model. All we need is an accuracy > 11%.\n",
        "\n",
        "First, let's define a function to plot our loss and accuracy curves. The function will also print the final loss and accuracy. Instead of using `verbose=1`, you can call the function."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "P68UKi78a0T-",
        "colab": {}
      },
      "source": [
        "def showClassificationResults(trainHistory):\n",
        "  \"\"\"Function to:\n",
        "   * Print final loss & accuracy.\n",
        "   * Plot loss & accuracy curves.\n",
        "\n",
        "  Args:\n",
        "    trainHistory: object returned by model.fit\n",
        "  \"\"\"\n",
        "\n",
        "  # Print final loss and accuracy\n",
        "  print(\"Final training loss: \" + str(trainHistory.history['loss'][-1]))\n",
        "  print(\"Final validation loss: \" + str(trainHistory.history['val_loss'][-1]))\n",
        "  print(\"Final training accuracy: \" + str(trainHistory.history['acc'][-1]))\n",
        "  print(\"Final validation accuracy: \" + str(trainHistory.history['val_acc'][-1]))\n",
        "\n",
        "  # Plot loss and accuracy curves\n",
        "  f = plt.figure(figsize=(10,4))\n",
        "  axLoss = f.add_subplot(121)\n",
        "  axAcc = f.add_subplot(122)\n",
        "  axLoss.plot(trainHistory.history['loss'])\n",
        "  axLoss.plot(trainHistory.history['val_loss'])\n",
        "  axLoss.legend(['Training loss', 'Validation loss'], loc='best')\n",
        "  axLoss.set_xlabel('Training epochs')\n",
        "  axLoss.set_ylabel('Loss')\n",
        "  axAcc.plot(trainHistory.history['acc'])\n",
        "  axAcc.plot(trainHistory.history['val_acc'])\n",
        "  axAcc.legend(['Training accuracy', 'Validation accuracy'], loc='best')\n",
        "  axAcc.set_xlabel('Training epochs')\n",
        "  axAcc.set_ylabel('Accuracy')"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "dU4bG_nYcTeR"
      },
      "source": [
        "Now train a linear model with an output layer and a hidden layer."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "5_gWbZxS5mFg",
        "colab": {}
      },
      "source": [
        "model = None\n",
        "# Define\n",
        "model = keras.Sequential()\n",
        "model.add(keras.layers.Dense(mnistData.shape[1],\n",
        "                             activation='linear',\n",
        "                             input_dim=mnistData.shape[1]))\n",
        "model.add(keras.layers.Dense(1, activation='linear'))\n",
        "# Compile\n",
        "model.compile(optimizer=\"adam\", loss='mse', metrics=['accuracy'])\n",
        "# Train\n",
        "trainHistory = model.fit(mnistData, mnistLabels, epochs=10, batch_size=100,\n",
        "                         validation_split=0.2, verbose=0)\n",
        "# Plot\n",
        "showClassificationResults(trainHistory)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "f8nF3XAnAres"
      },
      "source": [
        "Wow, that accuracy is terrible! What could the cause be?\n",
        "\n",
        "Hint: You followed the same procedure as for the previous regression problem. Do you need an adaptation for a classification problem? Experiment with the code above or skip to the solution below."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "dqnRGq2UCEYP"
      },
      "source": [
        "### Solution"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "DmvvQeJfCFc9"
      },
      "source": [
        "In regression, the last layer uses a linear activation function. In classification, the last layer cannot use a linear transform. Instead, one option is a softmax transform. Furthermore, in regression, the loss is calculated using MSE while in classification, loss is calculated using crossentropy. Before running your model, if you wrote a test to validate the output values, your test would detect the anomalous output. You'll look at such a test later. Move onto the next section to fix the loss calculation."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "296GJgdPkWDE"
      },
      "source": [
        "## Fixing Loss Calculation"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "A-mGfHlpDITS"
      },
      "source": [
        "Since your labels are integers instead of one-hot encodings, use `sparse_categorical_crossentropy` instead of `categorical_crossentropy` so that you avoid converting the integers to one-hot encoding."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "HFxuJSj2JhIZ"
      },
      "source": [
        "Retrain the model with the new loss calculation by running the following cell. Look through the code to note the changes. What do you think of the result?"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "vhfoEAR_gwFW",
        "colab": {}
      },
      "source": [
        "model = None\n",
        "# Define\n",
        "model = keras.Sequential()\n",
        "model.add(keras.layers.Dense(mnistData.shape[1], activation='linear',\n",
        "                             input_dim = mnistData.shape[1]))\n",
        "model.add(keras.layers.Dense(10, activation='softmax'))\n",
        "# Compile\n",
        "model.compile(optimizer=\"adam\",\n",
        "              loss='sparse_categorical_crossentropy',\n",
        "              metrics=['accuracy'])\n",
        "# Train\n",
        "trainHistory = model.fit(mnistData, mnistLabels, epochs=10, batch_size=100,\n",
        "                         validation_split=0.1, verbose=0)\n",
        "# Plot\n",
        "showClassificationResults(trainHistory)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "gr2QBQEvEN3D"
      },
      "source": [
        "Your loss curves are much better. Your accuracy has improved too. You're on the right track."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "-hNND_KIFyf7"
      },
      "source": [
        "## Train a Nonlinear Model"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "v_o9SEa3F0xy"
      },
      "source": [
        "Switch to a nonlinear model by modifying the code below to use relu activation functions instead of linear activation functions. Run the code. What do you observe?"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "bprM8t-ti-KQ",
        "colab": {}
      },
      "source": [
        "model = None\n",
        "# Define\n",
        "model = keras.Sequential()\n",
        "model.add(keras.layers.Dense(mnistData.shape[1], activation='', # use 'relu'\n",
        "                             input_dim=mnistData.shape[1]))\n",
        "model.add(keras.layers.Dense(10, activation='softmax'))\n",
        "# Compile\n",
        "model.compile(optimizer=\"adam\", loss='sparse_categorical_crossentropy',\n",
        "              metrics=['accuracy'])\n",
        "# Train\n",
        "trainHistory = model.fit(mnistData, mnistLabels, epochs=20, batch_size=100,\n",
        "                        validation_split=0.1, verbose=0)\n",
        "# Plot\n",
        "showClassificationResults(trainHistory)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "LodYblJbF673"
      },
      "source": [
        "The quality of the nonlinear model is significantly better than of the linear model. Progress! Move onto the next section."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "1u9z5zSIGF4H"
      },
      "source": [
        "## Adding a Second Layer"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "Xa_gtVEHJCON"
      },
      "source": [
        "Increasing the model's capacity significantly improved your results. Perhaps you can continue this strategy by adding a second relu layer. Run the following code cell to train the model with another relu layer."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "HgY8AFlWGHd2",
        "colab": {}
      },
      "source": [
        "model = None\n",
        "# Define\n",
        "model = keras.Sequential()\n",
        "model.add(keras.layers.Dense(mnistData.shape[1], activation='relu',\n",
        "                             input_dim = mnistData.shape[1]))\n",
        "model.add(keras.layers.Dense(mnistData.shape[1], activation='relu'))\n",
        "model.add(keras.layers.Dense(10,activation='softmax'))\n",
        "# Compile\n",
        "model.compile(optimizer=\"adam\", loss='sparse_categorical_crossentropy',\n",
        "              metrics=['accuracy'])\n",
        "# Train\n",
        "trainHistory = model.fit(mnistData, mnistLabels, epochs=10, batch_size=100,\n",
        "                        validation_split=0.1, verbose=0)\n",
        "# Plot\n",
        "showClassificationResults(trainHistory)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "2lcvRLzjJS6L"
      },
      "source": [
        "Guess what. Your previous model had training and validation accuracies of 100% and 95%. You can't do much better than that! So your new accuracy is about the same. How high can you push your accuracy? With this configuration the highest training and validation accuracies appear to be 100% and 96% respectively. Since the neural net returns similar accuracy with 1 or 2 layers, let's use the simpler model with 1 layer.\n",
        "\n",
        "Does your model begin to overfit the training data if you train for long enough? (Your model starts overfitting training data at the point when your validation loss starts increasing.)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "tDdWPO1AKsXx"
      },
      "source": [
        "## Check for Training/Validation Data Skew"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "UTGSClhnKutt"
      },
      "source": [
        "Our validation accuracy is a little worse than our training accuracy. While this result is always expected, you should check for typical errors. The commonest cause is having different distributions of data and labels in training and validation. Confirm that the distribution of classes in training and validation data is similar."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "5-8aUQ7eg2Z1",
        "colab": {}
      },
      "source": [
        "%hide_result # hides result of cell computation\n",
        "\n",
        "f = plt.figure(figsize=(10,3))\n",
        "ax = f.add_subplot(1,2,1)\n",
        "plt.hist(mnistLabels[0:len(mnistLabels)*8/10], bins=range(numClasses+1))\n",
        "plt.xticks(range(numClasses+1))\n",
        "ax2 = f.add_subplot(1,2,2,)\n",
        "plt.hist(mnistLabels[len(mnistLabels)*8/10:-1], bins=range(numClasses+1))\n",
        "plt.xticks(range(numClasses+1))"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "JYAlIiUBqe4H"
      },
      "source": [
        "## Apply Dropout Regularization"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "9UDeCe7Iqgc3"
      },
      "source": [
        "Dropout regularization is a common regularization method that removes a random selection of a fixed number of units in a network layer for a single gradient step. Typically, dropout will improve generalization at a dropout rate of between 10% and 50% of neurons. \n",
        "\n",
        "Try to reduce the divergence between training and validation loss by using dropout regularization with values between 0.1 and 0.5. Dropout does not improve the results in this case. However, at a dropout of 0.5, the difference in loss decreases, though both training and validation loss decrease in absolute terms."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "cellView": "both",
        "colab_type": "code",
        "id": "A0LNZvchsWJa",
        "colab": {}
      },
      "source": [
        "from keras import regularizers\n",
        "model = None\n",
        "# Define lambda\n",
        "dropoutLambda = 0.5 #@param\n",
        "# Define model\n",
        "model = keras.Sequential()\n",
        "model.add(keras.layers.Dense(mnistData.shape[1],\n",
        "                             input_dim=mnistData.shape[1],\n",
        "                             activation='relu'))\n",
        "model.add(keras.layers.Dropout(dropoutLambda,\n",
        "                               noise_shape=(1, mnistData.shape[1])))\n",
        "model.add(keras.layers.Dense(10, activation='softmax'))\n",
        "# Compile\n",
        "model.compile(optimizer = \"adam\",\n",
        "              loss = 'sparse_categorical_crossentropy',\n",
        "              metrics = ['accuracy'])\n",
        "# Train\n",
        "trainHistory = model.fit(mnistData,\n",
        "                        mnistLabels,\n",
        "                        epochs=30,\n",
        "                        batch_size=500,\n",
        "                        validation_split=0.1,\n",
        "                        verbose=0)\n",
        "# Plot\n",
        "showClassificationResults(trainHistory)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "FDP4RPSNxyHc"
      },
      "source": [
        "Sample results using dropout regularization after 30 epochs:\n",
        "\n",
        "Lambda | Training Loss | Validation Loss\n",
        "------- | ------------------------------------------------------\n",
        "0.1 | 0.99 | 0.95\n",
        "0.2 | 0.99 | 0.95\n",
        "0.3 | 0.99 | 0.95\n",
        "0.5 | 0.97 | 0.94"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "md6_n4woxgdQ"
      },
      "source": [
        "## Check Accuracy for Data Slices"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "JndFQG56xhYD"
      },
      "source": [
        "For classification problems, you should always check the metrics by class to ensure your model predicts well across all classes. Check accuracy on the 10 classes by running the next cell by using the function `sklearn.metrics.classification_report` from the scikit-learn library. In the output, the rows with indices 0 to 9 correspond to the classes for the labels 0 to 9. The columns \"Precision\", \"Recall\", and \"[F1-Score](https://en.wikipedia.org/wiki/F1_score)\" correspond to the respective classification metrics for each class. \"Support\" is the number of examples for the class in question. For example, for the label \"4\", when predicting on 464 examples labelled \"4\", the model has a precision of 0.98, a recall of 0.97, and a F1 score of 0.98.\n",
        "\n",
        "The classification metrics are very uniform across all classes, which is perfect. In your classification problem, in case any metric is lower for a class, then you should investigate why the model has lower-quality predictions for that class."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "YArLe5K8xjoE",
        "colab": {}
      },
      "source": [
        "from sklearn.metrics import classification_report\n",
        "mnistPred = model.predict_classes(x = mnistData)\n",
        "print(classification_report(mnistLabels, mnistPred))"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "XGaXjzW2ItTr"
      },
      "source": [
        "## Testing for Anomalous Values"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "Rkl5SPIsI3Bb"
      },
      "source": [
        "In the section [Train a Linear Model](https://colab.corp.google.com/google_src/cloud/karangill/mlcc/google3/engedu/ml/capitalg/colab/testing_debugging_classification.ipynb#scrollTo=B6AOgLcC5nwp), you debugged an incorrect calculation of loss. Before running your model, if you wrote a test to validate the output values, your test would detect the anomalous output. For example, you could test whether the distribution of predicted labels on the training dataset is similar to the actual distribution of training labels. A simple statistical implementation of this concept is to compare the standard deviation and mean of the predicted and actual labels.\n",
        "\n",
        "First, check the standard deviation and mean of the actual labels."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "F_WjpuqmZuAr",
        "colab": {}
      },
      "source": [
        "print(\"Mean of actual labels: \" + str(np.mean(mnistLabels)))\n",
        "print(\"Standard deviation of actual labels: \" + str(np.std(mnistLabels)))"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "W30mjNZUv8Gx"
      },
      "source": [
        "Write tests to check if the mean and standard deviation of the predicted labels falls within the expected range. The expected range defined in the tests below is somewhat arbitrary. In practice, you will tune the range thresholds to accommodate natural variation in predictions."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "P-XChYMVHFhn",
        "colab": {}
      },
      "source": [
        "class mlTest(unittest.TestCase): \n",
        "  '''Class to test statistics of predicted output on training data against\n",
        "     statistics of labels to validate that model predictions are in the]\n",
        "     expected range.\n",
        "  '''\n",
        "     \n",
        "  def testStd(self):\n",
        "    y = model.predict(mnistData)\n",
        "    yStd = np.std(y)\n",
        "    yStdActual = np.std(mnistLabels)\n",
        "    deltaStd = 0.05\n",
        "    errorMsg = 'Std. dev. of predicted values ' + str(yStd) + \\\n",
        "               ' and actual values ' + str(yStdActual) + \\\n",
        "               ' differs by >' + str(deltaStd) + '.'\n",
        "    self.assertAlmostEqual(yStd, yStdActual, delta=deltaStd, msg=errorMsg)\n",
        "\n",
        "  def testMean(self):\n",
        "    y = model.predict(mnistData)\n",
        "    yMean = np.mean(y)\n",
        "    yMeanActual = np.mean(mnistLabels)\n",
        "    deltaMean = 0.05\n",
        "    errorMsg = 'Mean of predicted values ' + str(yMean) + \\\n",
        "               ' and actual values ' + str(yMeanActual) + \\\n",
        "               ' differs by >' + str(deltaMean) + '.'\n",
        "    self.assertAlmostEqual(yMean, yMeanActual, delta=deltaMean, msg=errorMsg)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "Prq5XYuAKE0y"
      },
      "source": [
        "Run the following cell to train a model with the wrong loss calculation and execute the tests. The tests should fail."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "cellView": "both",
        "colab_type": "code",
        "id": "_51wIJhXKF68",
        "colab": {}
      },
      "source": [
        "#@title Train model and run tests\n",
        "\n",
        "model = None\n",
        "# Define\n",
        "model = keras.Sequential()\n",
        "model.add(keras.layers.Dense(mnistData.shape[1],\n",
        "                             activation='linear',\n",
        "                             input_dim=mnistData.shape[1]))\n",
        "model.add(keras.layers.Dense(1, activation='linear'))\n",
        "# Compile\n",
        "model.compile(optimizer=\"adam\", loss='mse', metrics=['accuracy'])\n",
        "# Train\n",
        "trainHistory = model.fit(mnistData, mnistLabels, epochs=10, batch_size=100,\n",
        "                         validation_split=0.1, verbose=0)\n",
        "\n",
        "suite = unittest.TestLoader().loadTestsFromTestCase(mlTest)\n",
        "unittest.TextTestRunner(verbosity=1, stream=sys.stderr).run(suite)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "LalmZjs7b0M5"
      },
      "source": [
        "Since the tests fail, check the data distribution of predicted labels for anomalies."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "11S1Mh6VbtgT",
        "colab": {}
      },
      "source": [
        "yPred = model.predict(mnistData)\n",
        "plt.hist(yPred, bins=range(11))"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "2vLmiLOob_zY"
      },
      "source": [
        "Given equally represented classes, the predicted labels are clearly skewed. From this plot, a possible explanation is that your loss calculation does not appear to be weighting all classes equally. This anomaly is a hint that your loss calculation is incorrect."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "r2dShXOwTe0B"
      },
      "source": [
        "## Optional: Pass Tests by Fixing Loss Calculation"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "K7UhxfMKTi_7"
      },
      "source": [
        "As an optional exercise, you can attempt to pass the tests by fixing the loss calculation. You will need to:\n",
        "1. Fix the loss calculation by setting the output layer's activation to `softmax`.\n",
        "1. Set the model's loss to `sparse_categorical_crossentropy`.\n",
        "1. Set the number of units in the output layer to 10 corresponding to the 10 classes.\n",
        "1. Adapt the tests to the modified output layer."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "W0lr3mzppHr1"
      },
      "source": [
        "## Conclusion\n",
        "\n",
        "The Colab demonstrated the following principles:\n",
        "\n",
        "* Calculate loss correctly for your problem.\n",
        "* Verify and unit test your engineered data.\n",
        "* Find the right model capacity through experimentation.\n",
        "* Find the best regularization through experimentation.\n",
        "* Check quality on data slices."
      ]
    }
  ]
}
